

import axios from "axios";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

NProgress.configure({ showSpinner: false });

const errorMessages = {
  401: "没有权限访问",
  403: "禁止访问",
  404: "资源找不到",
  500: "服务器故障",
};

const request = axios.create({
  baseURL: "/mock",
  headers: {},
  timeout: 10000,
});



// 请求拦截器
request.interceptors.request.use(
  (config) => {
    
    NProgress.start();

    
    return config;
  }
  
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    NProgress.done();

    
    if (response.data.code === 200) {
      // 功能成功，返回数据
      return response.data.data;
    }

    // 4. 统一进行错误提示
    const message = response.data.message || "未知错误，请求管理员";
  
    alert(message);
    return Promise.reject(message);
  },
  (error) => {
    NProgress.done();
    
    console.dir(error);
    let message = "未知错误，请求管理员";

    if (error.response) {
     
      
      message = errorMessages[error.response.status];
    } else {
      
      if (error.message.indexOf("Network Error") > -1) {
        message = "网络断开链接，请打开网络链接试试";
      } else if (error.message.indexOf("timeout") > -1) {
        message = "网速太慢了，打开4G网或连接WIFI试试";
      }
    }

    alert(message);
    return Promise.reject(message);
  }
);

export default request;
